﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

using Rio.Manager.Application.Utils;

using Telerik.Windows.Controls;

namespace Rio.Manager.Application.Behaviors
{
    public class FilterGridViewByTextBehavior : Behavior<TextBox>
    {
        #region Fields

        public static readonly DependencyProperty GridViewToFilterProperty = 
            DependencyProperty.Register("GridViewToFilter", typeof(RadGridView), typeof(FilterGridViewByTextBehavior), null);

        private StringFilterDescriptor _stringFilterDescriptor;

        #endregion Fields

        #region Constructors

        public FilterGridViewByTextBehavior()
            : base()
        {
        }

        #endregion Constructors

        #region Properties

        public RadGridView GridViewToFilter
        {
            get { return (RadGridView)GetValue(GridViewToFilterProperty); }
            set { SetValue(GridViewToFilterProperty, value); }
        }

        public StringFilterDescriptor StringFilterDescriptor
        {
            get
            {
                if (this._stringFilterDescriptor == null)
                {
                    this._stringFilterDescriptor = new StringFilterDescriptor(GridViewToFilter.Columns.OfType<GridViewDataColumn>());
                    GridViewToFilter.FilterDescriptors.Add(this._stringFilterDescriptor);
                }

                return this._stringFilterDescriptor;
            }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Called when [attached].
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.TextChanged += FilterTextBox_TextChanged;
        }

        /// <summary>
        /// Called when [detaching].
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.TextChanged -= FilterTextBox_TextChanged;
        }

        /// <summary>
        /// Handles the TextChanged event of the FilterTextBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.TextChangedEventArgs"/> instance containing the event data.</param>
        private void FilterTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            StringFilterDescriptor.FilterValue = AssociatedObject.Text;
            AssociatedObject.Focus();
        }

        #endregion Methods
    }
}